#include <assert.h>
#include <irrlicht.h>
#include "demo.h"
#include "fx_closer.h"


using namespace irr;
using namespace irr::core;
using namespace irr::scene;


static ISceneManager *sSceneManager = 0;
static ISceneNode *sSatelliitti = 0;
static ISceneNode *sSatelliitti2 = 0;
static ISceneNode *sKukka = 0;
static ISceneNode *sTaivas = 0;
static int inits = 0;

static void initSatellites(){
	sSatelliitti->setPosition(vector3df(0.0, 0.0, 0.0));
	sSatelliitti->setScale(vector3df(0.0, 0.0, 0.0));

	sSatelliitti2->setPosition(vector3df(-3.1, 0.4, 0.5));
}


bool CloserFx::init()
{
    if (!gIrrDevice || !gIrrDevice->getSceneManager())
        return false;

    //bool zipRes = gIrrDevice->getFileSystem()->addFileArchive("data_oldies_hallintaa.zip", false, false, io::EFAT_ZIP);
    //assert(zipRes);

    sSceneManager = gIrrDevice->getSceneManager()->createNewSceneManager();

    ISceneManager *sceneManager = sSceneManager;

    sceneManager->loadScene("data/oldies/closer.irr");

    //ISceneNode *light = sceneManager->getSceneNodeFromType(scene::ESNT_LIGHT);

    sSatelliitti = sceneManager->getSceneNodeFromName("satelliitti");
	sSatelliitti2 = sceneManager->getSceneNodeFromName("satelliitti2");
	initSatellites();
	

	sKukka = sceneManager->getSceneNodeFromName("kukka");
	sKukka->setPosition(vector3df(-0.2, -0.6, 1.0));
	//sKukka->setRotation(vector3df(90.0, 0.0, 90.0));
	sKukka->setScale(vector3df(0.0, 0.0, 0.0));

    sceneManager->addCameraSceneNode();
    vector3df cameraPosition(-0.6, -1.0, 2);
    sceneManager->getActiveCamera()->setPosition(cameraPosition);
	sceneManager->getActiveCamera()->setTarget(sSatelliitti->getPosition());
	
    mInitialized = true;
    return true;
}


void CloserFx::render(double time, int timeMs)
{   
	float t = (float)(time - mFxStartTime);
	if(t>=17 && inits == 0){
		initSatellites();
		++inits;
	}

	vector3df eulerAngles(0.0f, 0.0f, (float)gTimeMs / 20.0f);
	sSatelliitti->setRotation(eulerAngles);
	vector3df pos = sSatelliitti->getPosition();
	pos.X -= 0.010;
	//pos.Y -= 0.010;
	pos.Z += 0.010;
	sSatelliitti->setPosition(pos);
	vector3df scl = sSatelliitti->getScale();
	scl.X -= 0.040;
	scl.Y -= 0.040;
	scl.Z += 0.040;

	/*if(scl.Z >= 1.8){
		scl.Z = 1.8;
		pos.X += 0.010;
		sSatelliitti->setPosition(pos);
	}*/
	sSatelliitti->setScale(scl);

	pos = sSatelliitti2->getPosition();
	pos.X += 0.008;
	sSatelliitti2->setPosition(pos);

	vector3df sclK = sKukka->getScale();
	sclK.X += 0.0050;
	sclK.Y += 0.0050;
	sclK.Z += 0.0050;
	sKukka->setScale(sclK);

	
	sSceneManager->drawAll();
}


void CloserFx::deinit()
{
    sSceneManager->drop();
    mInitialized = false;
}
